package com.nidu.demo.web.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.fastjson2.JSONObject;
import com.nidu.demo.common.constants.RequestHeaderConstants;
import com.nidu.demo.common.enums.UserTypeEnum;
import com.nidu.demo.common.exception.ErrorCode;
import com.nidu.demo.web.config.WebProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class WebUtils {

    private static WebProperties properties;

    public WebUtils(WebProperties webProperties) {
        WebUtils.properties = webProperties;
    }

    public static Integer getLoginUserType(HttpServletRequest request) {
        if (request == null || properties == null) {
            return null;
        }
        // 1. 优先，从 Attribute 中获取
        Integer userType = (Integer) request.getAttribute(RequestHeaderConstants.REQUEST_ATTRIBUTE_LOGIN_USER_TYPE);
        if (userType != null) {
            return userType;
        }
        // 2. 其次，基于 URL 前缀的约定
        String requestUri = request.getRequestURI();

        if (requestUri.startsWith(properties.getAdminApi().getPrefix())) {
            return UserTypeEnum.ADMIN.getType();
        }
        
        if (requestUri.startsWith(properties.getAppApi().getPrefix())) {
            return UserTypeEnum.MEMBER.getType();
        }
        
        return null;
    }

    /**
     * 获得租户编号，从 header 中
     * 考虑到其它 framework 组件也会使用到租户编号，所以不得不放在 WebFrameworkUtils 统一提供
     *
     * @param request 请求
     * @return 租户编号
     */
    public static Long getTenantId(HttpServletRequest request) {
        String tenantId = request.getHeader(RequestHeaderConstants.HEADER_TENANT_ID);
        return NumberUtil.isNumber(tenantId) ? Long.valueOf(tenantId) : null;
    }

    public static void writeJSON(HttpServletResponse response, ErrorCode errorCode) {
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            Response respResult = Response.buildFailure(errorCode.getCode(),
                    errorCode.getMessage());
            writer.write(JSONObject.toJSONString(respResult));
            writer.flush();
        } catch (IOException e) {
            log.error("返回数据异常", e);
        } finally {
            IoUtil.close(writer);
        }
    }

}
